<?php
/**
 * Created by PhpStorm.
 * User: 兔白白
 * Date: 2021/3/27
 * Time: 19:38
 */

namespace app\index\controller;



use think\facade\Cache;

class Api extends IndexBase
{

    public $title = '盲人按摩.txt';

    //首页
    function Index(){
        $url = 'https://m.cyewx.com/206/206334/all.html';
        $html = $this->getController($url);
        dump(strlen($html));
        //  <p><a href='/206/206334/49595742.html'>第1章 恢复视力</a></p>
        $patten = "#<a href\=\'(.*?)\'>(.*?)</a>#";
        preg_match_all($patten,$html,$arr);
        $data = [];
        foreach ($arr[1] as $k=>$v){
            $data[] = [
                'name'=>$arr[2][$k],
                'url'=>'https://m.cyewx.com'.$arr[1][$k],
            ];
        }
        Cache::set('mangren',$data);
        dump("保存章节：".count($data).'成功');
    }


    //获取单章
    // http://www.thinkadmin.cn/index/api/getItem?id=30
    function getItem(){
        $index = input('id');
        $id = $index ? : (Cache::get('index')?:1);
        $path = ROOT_PATH.'/data/';
        $list = Cache::get('mangren');
        $count = count($list);
        if($id==$count){
            exit("下载完成");
        }
        $item = $list[$id-1];
        dump($item);
        $is = Cache::get('error')?1:0;
        dump($is);
//        $content = $this->getController($item['url']);
        $content = $this->getItemContent($item,$is);
        if(empty($content)){
            Cache::set('error',1);
        }else{
            Cache::set('error',0);
        }
        dump(strlen($content));
        $fp = fopen($path.$this->title,'a');
        if(fwrite($fp,$content)){
            $id++;
            Cache::set('index',$id);
        };
        fclose($fp);
        if($id>30){
            $mat = mt_rand(10,30);
        }else{
            $mat = mt_rand(1,3);
        }
        dump("{$mat}秒后再请求");
        header("refresh:{$mat};url=".url('getItem'));
    }

    function getItemContent($item=[],$is=false){
//        $list = Cache::get('mangren');
//        $item = $list[1];
//        $url = 'https://m.cyewx.com/206/206334/49595742.html';

        $url = $item['url'];
        $html = $this->getController($url,$is);
        //匹配下一页内容
        // <a href="/206/206334/49688455_2.html" id="pt_next" class="Readpage_down js_page_down">下一页</a>
        $pattern = '#<a href="(.*?)" id="pt_next"#';
        $_html = '';
        if(preg_match($pattern,$html,$arr)){
            $_url = 'https://m.cyewx.com'.$arr[1];
            $_html = $this->getController($_url,$is,$url);
            $_html = $this->guolv($_html);
            dump("第二页内容：".strlen($_html));
            if(empty($_html)){
                $html = '';
            }
        }
        $html = $this->guolv($html);
        dump($html);

        if($_html){
            $html.=$_html;
        }
        if($is){
            dump("重新加载");
        }
        return $html;
    }

    function guolv($html){
        $html = str_replace('<br />',"\r\n",$html);
        $html = strip_tags($html);
        $html = $this->get_between($html,'cranbe1();',"『加入书签，方便阅读』");
        $search = ['&nbsp;'];
        $replace = ['  '];
        $html = str_replace($search,$replace,$html);
        return $html;
    }

      function getController($url,$is=false,$rrr=''){
           if(!$is && Cache::has($url)){
               return Cache::get($url);
           }
           if(mt_rand(1,2)==1){
               $data = $this->curl($url,$rrr);
           }else{
            $data = file_get_contents($url);
           }
           Cache::set($url,$data);
           return $data;
      }

      function curl($url='',$rrr=''){
//            $url = 'https://m.cyewx.com/206/206334/49688455.html';
            $op = [
                'type'=>'get',
                'header'=>[
                    'Host: m.cyewx.com',
                    'Cookie: Hm_lvt_730320aa3863be5efba5e5492ac72ef8=1616832410; UM_distinctid=17872b8b25822e-09f642a100678c-45410429-100200-17872b8b25939b; CNZZDATA1279321542=620342522-1616828748-%7C1616850653; Hm_lpvt_730320aa3863be5efba5e5492ac72ef8=1616855010',
                    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                    'Sec-Fetch-Dest: document',
                    'Sec-Fetch-Mode: navigate',
                    'Sec-Fetch-Site: none',
                    'Sec-Fetch-User: ?1',
                    'Upgrade-Insecure-Requests: 1',
                    'User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Mobile Safari/537.36',

                ],
            ];
            if($rrr){
                $op['header'][] = 'Referer: '.$rrr;
            }
            dump($url);
            dump($op);
            $html = $this->httpRequest($url,$op);
            return $html;
      }

    /**
     * curl HTTP请求
     * @param  [type]  $url      网址
     * @param  string $opt 提交参数
     * @param  [type]  &$header  取回的头信息
     * @param  boolean $redirect 是否重定向
     * @param  boolean $ssl 验证https证书
     * @return [type]            返回信息
     */
    function httpRequest($url, $opt = 'GET', &$code = null, &$header = null, $redirect = true, $ssl = false)
    {
        //初始化
        $ch = curl_init($url);
        //配置设置
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $ssl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $ssl);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirect);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 #返回结果
        curl_setopt($ch, CURLOPT_HEADER, true);                         #显示头信息
        // curl_setopt($ch, CURLOPT_ENCODING ,'gzip');
        if (is_array($opt)) {
            //转小写
            $opt = array_change_key_case($opt, CASE_LOWER);
            if (isset($opt['type']) && strtoupper($opt['type']) == 'POST') {
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, (isset($opt['data']) ? $opt['data'] : ''));
            }
            if (array_key_exists('ua', $opt))
                curl_setopt($ch, CURLOPT_USERAGENT, $opt['ua']);
            if (array_key_exists('header', $opt)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, (array)$opt['header']);
            }
            if (array_key_exists('cookie', $opt))
                curl_setopt($ch, CURLOPT_COOKIE, $opt['cookie']);
            if (array_key_exists('referer', $opt))
                curl_setopt($ch, CURLOPT_REFERER, $opt['referer']);
        } else {
            if (strtoupper((string)$opt) == 'POST')
                curl_setopt($ch, CURLOPT_POST, true);
        }
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $result = curl_error($ch);
        } else {
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $length = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $length);

            $result = substr($result, $length);
        }
        //释放
        curl_close($ch);
        return $result;
    }


      //文本取中间
    function get_between($input, $start, $end) {
        $substr = substr($input, strlen($start)+strpos($input, $start),

            (strlen($input) - strpos($input, $end))*(-1));

        return $substr;

    }
}